import * as vscode from 'vscode';
import * as WORKSPACE_UTILS from './workspace';
import { platformCmd, registerBasic, outputChannel } from './common';
const path = require('path');

/**
 * 获取模块名称
 * @param uri 表示磁盘上文件的通用资源标识符 或其他资源，例如无标题资源。
 * @returns
 */
const getAppName = (uri: vscode.Uri): string => {
	// 获取当前选中的文件/文件夹路径
	const fsPath = uri.fsPath;
	const folderName = path.basename(fsPath);
	return folderName;
};

/**
 * 是否有效国模爱哭
 * @param appName 模块名称
 * @returns
 */
const validApp = (appName: string): boolean => {
	return /^dmp-(.*)$/.test(appName);
};

/**
 * TODO　选择开发环境／测试环境
 * TODO　多应用同时启动
 * 注册本地启动菜单
 *
 */
export const register_Menus_Dev = (): vscode.Disposable => {
	return registerBasic('menu:dev', async (uri: vscode.Uri) => {
		if (!uri) {
			return;
		}
		const folderName = getAppName(uri);
		if (validApp(folderName)) {
			outputChannel.appendLine(`🚀 ~正在执行本地启动[${folderName}]...`);
			let terminal = WORKSPACE_UTILS.getTerminalOpened()?.[0];
			if (!terminal) {
				terminal = vscode.window.createTerminal(`wit-helper`);
			}
			const rootPath = WORKSPACE_UTILS.getRootPath();
			try {
				// 获取要操作的文件路径
				const filePath = vscode.Uri.file(path.resolve(rootPath, './build/dev-modules.js')); // 替换为实际路径
				await vscode.workspace.fs.writeFile(filePath, Buffer.from(`module.exports=['${folderName}']`));
				terminal.sendText(`${platformCmd} ${rootPath}`); // 切换到工作区目录
				terminal.sendText(`npm run dev`); // 切换到工作区目录
			} catch (e) {
				vscode.window.showErrorMessage(`🚀 ~读取dev-module.js配置文件失败`);
			}
		} else {
			vscode.window.showWarningMessage('请选择正确的文件夹');
		}
	});
};

/**
 * 注册打包菜单
 * TODO 多应用同时打包
 */
export const register_Menus_Build = (): vscode.Disposable => {
	return registerBasic('menu:build', (uri: vscode.Uri) => {
		if (!uri) {
			return;
		}
		const folderName = getAppName(uri);
		if (validApp(folderName)) {
			outputChannel.appendLine(`🚀 ~正在执行本地构建[${folderName}]...`);
			let terminal = WORKSPACE_UTILS.getTerminalOpened()?.[0];
			if (!terminal) {
				terminal = vscode.window.createTerminal(`wit-helper`);
			}
			terminal.sendText(`${platformCmd} ${WORKSPACE_UTILS.getRootPath()} && npm run build:prod:${folderName}`); // 切换到工作区目录
		} else {
			vscode.window.showWarningMessage('请选择正确的文件夹');
		}
	});
};

/**
 * 注册所有命令
 * @param context
 */
export const register = (context: vscode.ExtensionContext): void => {
	// 初始化项目依赖
	context.subscriptions.push(register_Menus_Dev());
	context.subscriptions.push(register_Menus_Build());
};
